/**************************************************************************************
Class Name              : CaseManagerController
Created By              : Kalyani Nemala
Created on              : 01/31/2013
Description             : Supports the functionality of Case Manager screen
Version                 : 1.0
***************************************************************************************/

/***************************************************************************************
Modified By : Sreekanth SV Vegi
Modified Date : Feb 19, 2013
Modification :  Logic to handle Clear Button and Username on Multiselect picklist
***************************************************************************************/

public with sharing class CaseManagerController{
    
    /*Declaration of variables*/
    transient private list<User> listUserExistingUsersInSelectedQueue;
    private list<SelectOption> listSelectOptionExistingUsers;
    list<SelectOption> listSelectOptionExistingGroupsForSelectedUser; 
    set<Id> stIdPublicGroups;
    map<Id, User> mapUserMatchedtoSearch;
    
    /*Getter & Setter methods*/
    public list<SelectOption> listSelOptQueues{get; set;}
    public string strSelectedQueues{ get; set; }
    public string strNameOfSelectedUser{get; set;}
    public list<SelectOption> listSelOptUsersAvailableForSelection{get; set;}
    public list<SelectOption> listSelOptSelectedUsers{ get; set;}
    public string strSelectedSearchOptionForQueueTab{get; set;}
    public list<SelectOption> listSelectOptionSearchOptions{ set; get;}
    public string strSearchKeyForQueue{get; set;}
    public boolean boolShowDropDownOfUsers{get; set;} 
    public boolean boolShowMessagesForQueueTab{get; set;}
    public list<SelectOption> listSelectOptionUsersMatchingSearch{get; set;}
    public boolean boolShowUserTabMessages{get; set;}
    public list<SelectOption> listSelectOptionGroupsMultiSelectRight{get; set;}
    public list<SelectOption> listSelectOptionGroupsMultiSelectLeft{get; set;}
    public string strSearchKeyForUser{get; set;}
    public string strSelectedSearchOptionForUserTab{get; set;}
    public string strIdOfSelectedUser{get;set;}
    //Added by Sreekanth SV Vegi
    public string buttonValue{get;set;}
    public string buttonValueforSecondTab{get;set;}
    //Ended by Sreekanth SV Vegi
    
    /*Constructor that sets defaults queues, search options*/
    public CaseManagerController(){
        listSelOptSelectedUsers                = new list<SelectOption>();
        listSelOptUsersAvailableForSelection   = new list<SelectOption>();
        strNameOfSelectedUser                  = '';
        /*Set the West Case Management(CM -) Queues for picklist of Queue*/
        setQueues();
        /*Set the Criteria that can be used to search*/
        setSearchOptions();
        /*Set the default users when nothing is searched for*/
        //setUsers(); //Commented because call it only when string queue name is selected
        listSelectOptionExistingUsers          = new list<SelectOption>();
        listSelectOptionGroupsMultiSelectLeft  = new list<SelectOption>();
        listSelectOptionGroupsMultiSelectRight = new list<SelectOption>();
        listSelectOptionUsersMatchingSearch    = new list<SelectOption>();
        listUserExistingUsersInSelectedQueue   = new List<User>(); 
        
        listSelectOptionExistingGroupsForSelectedUser = new list<SelectOption>();
        mapUserMatchedtoSearch=new map<Id, User>();
        
        //Added by Sreekanth SV Vegi
        buttonValue='Find';
        buttonValueforSecondTab='Find';
        //Ended by Sreekanth SV Vegi
        
    }
    /* Fetch all the first 100 users */
    public void setUsers(){
        list<User> lstUsersToDisplay;
        list<User> lstUsersDisplayed;
        list<Group> grpUsersInQueue = [Select Id from Group where type='Queue' and Name= :strSelectedQueues];
        Set<Id> setIds = new Set<Id>();
        for(Group objGroup :grpUsersInQueue){
            setIds.add(objGroup.Id);
        }   
        lstUsersToDisplay = [Select Id, Name from User where Id not in(Select UserOrGroupId from GroupMember where GroupId in :setIds ) and  isActive=True limit 100];
        map<String, User> mapUserNames = new map<String, User>();  
        for(User usersToDisplay : lstUsersToDisplay ){
            mapUserNames.put(usersToDisplay.Name, usersToDisplay);
        }
        lstUsersDisplayed = mapUserNames.values();
        lstUsersDisplayed.sort();
        for(User users:lstUsersDisplayed){
            /*Iterate the list and add Name to Available Selection*/
            String LoopUserName = users.Name;
            listSelOptUsersAvailableForSelection.add(new SelectOption(LoopUserName, LoopUserName));
        }
         listSelOptUsersAvailableForSelection = convertListOfNamesinUserToSelectOption(lstUsersDisplayed);
    }
    
    /*Fetch all the names of Queues related to West Case Management(CM - ) and show them in picklist*/
    public void setQueues(){
        
        list<QueueSobject> listCaseQueues;
        list<QueueSobject> lstQueueSobject;
        listSelOptQueues = new list<SelectOption>();
        
        /*Fetch the Queue Names*/
        lstQueueSobject = [Select Id, QueueId,Queue.Name, SobjectType from QueueSobject where Queue.Name like '%CM - %' order by Queue.Name desc];
        map<String, QueueSobject> mapQueueNames = new map<String, QueueSobject>();
        for( QueueSobject objQueues : lstQueueSobject){
            mapQueueNames.put(objQueues.Queue.Name, objQueues);
        }
        
        /*List of Queue Names that needs to be shown in picklist*/
        listCaseQueues = mapQueueNames.values();
        listCaseQueues.sort();
        
        listSelOptQueues.add(new SelectOption('', 'None'));
        for(QueueSobject loopQueue:listCaseQueues){
            /*Iterate the list and add Queue Name to SelectOption*/
            String LoopQueueName = loopQueue.Queue.Name;
            listSelOptQueues.add(new SelectOption(LoopQueueName, LoopQueueName));
        }
    }   
    
    /*Search criteria for users on Queue Assignment tab and User assignment tab*/
    public void setSearchOptions(){
        listSelectOptionSearchOptions = new list<SelectOption>();
        listSelectOptionSearchOptions.add(new SelectOption('FirstName','First Name'));
        listSelectOptionSearchOptions.add(new SelectOption('LastName','Last Name'));
        listSelectOptionSearchOptions.add(new SelectOption('Name','User Name'));
    }
    /*Based on the Queue that is selected, Users in that queue should be displayed*/
    public void updateUsersInMultiSelectListBasedOnQueue(){
        boolShowMessagesForQueueTab=false;
        if(strSelectedQueues!=NULL && strSelectedQueues!=''){
        Group grpQueueDetails = new Group();    
        try{    
        grpQueueDetails = [Select Id from Group where type='Queue' and Name= :strSelectedQueues];   
        }Catch(Exception qE){
            System.debug('Error while querying Group'+qE.getMessage());
        }
        /*If the Queue Name is not empty update the users in that queue*/
        if(strSelectedQueues!=NULL){
            updateUsersInTheGroup(grpQueueDetails);
          }
        else{
        /*If the queue name does not exist, throw an error*/
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error, 'No Such Queue'));
            boolShowMessagesForQueueTab=true;
            }
        /*Search area for users*/
        if(strSearchKeyForQueue != Null && strSearchKeyForQueue != ''){
           updateUsersAvailableForSelection();
        }
        else{
         setUsers();
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Only the first 100 Available Users are displayed. Please refine your search criteria'));
         boolShowMessagesForQueueTab = true;
        } 
        }
        else{
            listSelOptSelectedUsers.clear();
            listSelectOptionExistingUsers.clear();
            listSelOptUsersAvailableForSelection.clear();
            strNameOfSelectedUser = '';
            }     
        }
    
    /*Update Users from Queue that has been Selected*/
    public void updateUsersInTheGroup(Group grpQueueDetails ){
         map<Id, User> mapUserExistingInSelectedQueue = new map<Id, User>([Select Id, Name from User where Id IN (Select UserOrGroupId from GroupMember where GroupId =: grpQueueDetails.Id )]);
         listUserExistingUsersInSelectedQueue = mapUserExistingInSelectedQueue.values();
         listSelOptSelectedUsers = convertListOfNamesinUserToSelectOption(listUserExistingUsersInSelectedQueue);
         listSelectOptionExistingUsers = listSelOptSelectedUsers.clone();
         system.debug('\n listSelectOptionExistingUsers: '+ listSelectOptionExistingUsers +'\n listSelOptSelectedUsers: '+listSelOptSelectedUsers);
    }

    /* Method to Add Names list of users to Select Option */
    public list<SelectOption> convertListOfNamesinUserToSelectOption(list<User> listUsers){
        list<SelectOption> listSelectOptionUsers = new List<SelectOption>();
        for(User loopUser: listUsers){
            listSelectOptionUsers.add(new SelectOption(loopUser.id,loopUser.Name));
        }
        system.debug('listSelectOptionUsers: '+listSelectOptionUsers);
        return listSelectOptionUsers;
    }
    
    /*Action for cancel button*/
    public PageReference redirectToConsoleHome(){
        return (new PageReference('/apex/ConsoleHome_VF'));
    }

    /* Find the Queues to which the User belongs to */
    public void findQueues(){
        boolShowUserTabMessages = false;
        if( strSearchKeyForUser != NULL && strSearchKeyForUser != '' ){
            string strQuery = 'Select id, Name from User where '+strSelectedSearchOptionForUserTab+' LIKE \'%' + strSearchKeyForUser + '%\'';
            list<User> listUserMatchedUsers = Database.query(strQuery);
            system.debug('\n strQuery: '+strQuery+'\n listUserMatchedUsers: '+listUserMatchedUsers);
            if(listUserMatchedUsers.isEmpty()){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'No users found'));
                boolShowUserTabMessages = true;
                //Added by Sreekanth SV Vegi
                buttonValueforSecondTab='Clear';
                //Ended by Sreekanth SV Vegi
            }
            else{
              mapUserMatchedtoSearch.clear();
              for(User loopUserMatchedtoSearch: listUserMatchedUsers){
                mapUserMatchedtoSearch.put(loopUserMatchedtoSearch.id,loopUserMatchedtoSearch);
              }
                boolShowDropDownOfUsers=true;
                strIdOfSelectedUser = listUserMatchedUsers.get(0).Id;
                strNameOfSelectedUser = listUserMatchedUsers.get(0).Name;
                listSelectOptionUsersMatchingSearch = convertListOfNamesinUserToSelectOption(listUserMatchedUsers);
                System.debug('==================>'+listSelectOptionUsersMatchingSearch);
            }
            updateQueues();
        }
        else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please Enter a search Text'));
            boolShowUserTabMessages = true;
        }
        }
    /*Update queues when the user is added or removed*/ 
        public void updateQueues(){
         system.debug('strIdOfSelectedUser: '+strIdOfSelectedUser);
        if(strIdOfSelectedUser != NULL && strIdOfSelectedUser != ''){
            listSelectOptionGroupsMultiSelectRight.clear();
            listSelectOptionGroupsMultiSelectLeft.clear();
            String strGroupName;
            boolean boolUserIsPartOfGroup;
           
            /*Get the UserId of selected Users*/
            Set<Id> setUserIdsToGetGroup = new Set<Id>();
            list<User> lstSelectedUsers = [Select Id,Name from User where Id = :strIdOfSelectedUser];
          //Added by Sreekanth SV Vegi  
            strNameOfSelectedUser=lstSelectedUsers.get(0).Name;
          //Ended by Sreekanth SV Vegi
            for(User objGroupIds:lstSelectedUsers){
                        setUserIdsToGetGroup.add(objGroupIds.Id);
                }
            list<QueueSobject> objQueue = [Select Id, QueueId, Queue.Name from QueueSobject where SobjectType='Case' and QueueId in (Select GroupId from GroupMember where UserOrGroupId in :setUserIdsToGetGroup)];
           Set<String> setAvailableQueueNames = new Set<String>();
           for(QueueSobject loopQueue:objQueue){
            /*Iterate the list and add Queue Name to SelectOption*/
            String LoopQueueName = loopQueue.Queue.Name;
            setAvailableQueueNames.add(LoopQueueName);
            listSelectOptionGroupsMultiSelectRight.add(new SelectOption(LoopQueueName, LoopQueueName));
            }
            list<QueueSobject> objAvailableQueues = [Select Queue.Name from QueueSobject where SobjectType='Case' and Queue.Name like '%CM - %'and Queue.Name not in :setAvailableQueueNames];
        
            for(QueueSobject loopAvailableQueues:objAvailableQueues){
                String loopAvailableQueueName = loopAvailableQueues.Queue.Name;
                listSelectOptionGroupsMultiSelectLeft.add(new SelectOption(loopAvailableQueueName, loopAvailableQueueName));
        }
        }   
        listSelectOptionExistingGroupsForSelectedUser = listSelectOptionGroupsMultiSelectRight.clone();
       }
        
    /*To modify the users selected in the queue*/       
    public void modifyUsersInQueue(){
     boolShowMessagesForQueueTab = false;
        if( strSelectedQueues != NULL && strSelectedQueues != '' ){
            system.debug('\n listSelOptSelectedUsers: '+listSelOptSelectedUsers+'\n listSelectOptionExistingUsers: '+listSelectOptionExistingUsers);
            list<String> listStringIdsExistingUsersInSelectedTenant = getValuesOfSelectOption(listSelectOptionExistingUsers);
            if(listSelOptSelectedUsers != listSelectOptionExistingUsers){
                list<String> listStrIdsOfSelectedUsers = getValuesOfSelectOption(listSelOptSelectedUsers);system.debug('\n listStrIdsOfSelectedUsers: '+listStrIdsOfSelectedUsers+'\n listStringIdsExistingUsersInSelectedTenant: '+listStringIdsExistingUsersInSelectedTenant);
                list<User> addedUsers= getAddedUsers(listStrIdsOfSelectedUsers,listStringIdsExistingUsersInSelectedTenant);
                list<QueueSobject> lstQueueGroups = [Select Id, QueueId, Queue.Name from QueueSobject Where SobjectType='Case' And Queue.Name = :strSelectedQueues];
                ID idSelectedTenantGroup = lstQueueGroups != NULL ? (lstQueueGroups[0].QueueId != NULL ? lstQueueGroups[0].QueueId : NULL) : NULL;
                try{
                    if(!addedUsers.isEmpty()){
                        addUsersToGroup(idSelectedTenantGroup,addedUsers);
                    }
                    deleteUsersFromGroup(listStringIdsExistingUsersInSelectedTenant,listStrIdsOfSelectedUsers,idSelectedTenantGroup);
                    listSelectOptionExistingUsers = listSelOptSelectedUsers.clone();
                    boolShowMessagesForQueueTab = true;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, +' User Queue is modified'));
                }
                catch(Exception E){
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error when saving users to '+strNameOfSelectedUser));
                }
            }
            else{
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'No Changes made'));
                boolShowMessagesForQueueTab = true;
            }
        }
        else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Please Select a Queue'));
            boolShowMessagesForQueueTab = true;
        }
 }
    
    /* Method to get the selected Values from SelectOption */
    public list<String> getValuesOfSelectOption(list<SelectOption> listSelectOption){
        list<String> listStrValues = new List<String>();
        for(SelectOption loopSelectOption: listSelectOption)
            listStrValues.add(loopSelectOption.getValue());
        return listStrValues;
    }
    
    /*Get the list of users added*/
    public List<User> getAddedUsers(List<String> newUserList, List<String> oldUserList){
        if( oldUserList != NULL && newUserList != NULL)
            return [select id, Name from User where Id =: newUserList AND Id !=: oldUserList];
        return NULL;
    }
    
   /*Adding the selected users to the selected queue*/ 
   public void addUsersToGroup(Id IdGroup, List<User> listUserstoAdd){
        if( IdGroup != NULL && listUserstoAdd != NULL ){
            list<GroupMember> listGrpMemToBeAdded = new List<GroupMember>();
            list<PermissionSetAssignment> listPermSetAssignToBeAdded = new List<PermissionSetAssignment>();
            set<ID> stIDAddedUsers = new set<ID>();
            Set<ID> setPermissionSetIDs = new Set<ID>();
            for(User userToAdd: listUserstoAdd)
            {
                GroupMember groupMembershipTobeAdded = new GroupMember();
                groupMembershipTobeAdded.GroupId = IdGroup;
                groupMembershipTobeAdded.UserOrGroupId = userToAdd.id;
                listGrpMemToBeAdded.add(groupMembershipTobeAdded);
            }
            system.debug('listGrpMemToBeAdded: '+listGrpMemToBeAdded + '\n listPermSetAssignToBeAdded: ' + listPermSetAssignToBeAdded);
            try{
                insert listGrpMemToBeAdded;
                list<PermissionSetAssignment> listPermSetAssignExisting = [Select id, AssigneeID, PermissionSetID from PermissionSetAssignment where AssigneeID =: stIDAddedUsers AND PermissionSetID =: setPermissionSetIDs];
                if(!listPermSetAssignExisting.isEmpty()){
                  for(integer i=0; i< listPermSetAssignToBeAdded.size(); i++){
                    for(PermissionSetAssignment loopPermSetAssignExisting: listPermSetAssignExisting){
                      if(listPermSetAssignToBeAdded[i].AssigneeId == loopPermSetAssignExisting.AssigneeId && listPermSetAssignToBeAdded[i].PermissionSetId == loopPermSetAssignExisting.PermissionSetId)
                        listPermSetAssignToBeAdded.remove(i);
                    }
                  }
                }
                
                if(listPermSetAssignToBeAdded != NULL && !listPermSetAssignToBeAdded.isEmpty())
                  insert listPermSetAssignToBeAdded;
            }
            catch(DMLException dmlE){
                system.debug('Exception: '+dmlE);
            }
        }
    } 
        public void deleteUsersFromGroup(list<String> oldUserList, list<String> newUserList,Id IdGroup){
        if(IdGroup != NULL && newUserList != NULL && oldUserList != NULL){
            List<GroupMember> removedGroupMembership = [Select id, UserorGroupId, GroupId from GroupMember where UserorGroupId IN (select id from User where Id =: oldUserList AND Id !=: newUserList) AND GroupId =: IdGroup];
            system.debug('removedGroupMembership: '+removedGroupMembership);
            
            if(!removedGroupMembership.isEmpty()){
                delete removedGroupMembership;
            }
        }
    }
    
  public void modifyQueues(){
    system.debug('The execution has entered into ModifyQueues');
    if(strIdOfSelectedUser == NULL || strIdOfSelectedUser == ''){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Please enter Search Text'));
        }
        else{
            system.debug('\n listSelectOptionExistingGroupsForSelectedUser: ' + listSelectOptionExistingGroupsForSelectedUser + '\n listSelectOptionGroupsMultiSelectRight: ' + listSelectOptionGroupsMultiSelectRight);
            System.debug('If the Queue has changed'+' Old ' +listSelectOptionExistingGroupsForSelectedUser +'New ' +listSelectOptionGroupsMultiSelectRight);
            if(listSelectOptionExistingGroupsForSelectedUser == listSelectOptionGroupsMultiSelectRight){
                System.debug('If the Queue has not changed'+' Old ' +listSelectOptionExistingGroupsForSelectedUser +'New ' +listSelectOptionGroupsMultiSelectRight);
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Content Not Modified'));
            }
            else{
               list<SelectOption> listExistingUsersToDelete = listSelectOptionExistingGroupsForSelectedUser.clone();
               list<SelectOption> listNewUsersToDelete = listSelectOptionGroupsMultiSelectRight.clone();
               System.debug('Users to be deleted' +listExistingUsersToDelete +'Users to be deleted' +listNewUsersToDelete);
                addUserToGroups(listSelectOptionExistingGroupsForSelectedUser ,listSelectOptionGroupsMultiSelectRight);//addUserToGroups(listGrpTenants, listStrAddedGroupIds);
               deleteUserFromGroups(listExistingUsersToDelete,listNewUsersToDelete );
               System.debug('Users to be deleted' +listExistingUsersToDelete +'Users to be deleted' +listNewUsersToDelete);
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Queues have been modified')); //for ' + strNameOfSelectedUser));
                listSelectOptionExistingGroupsForSelectedUser = listSelectOptionGroupsMultiSelectRight.clone();
                system.debug('\n listSelectOptionGroupsMultiSelectRight: '+ listSelectOptionGroupsMultiSelectRight + '\n listSelectOptionExistingGroupsForSelectedUser: ' +listSelectOptionExistingGroupsForSelectedUser );
            }
        }
        boolShowUserTabMessages = true;
}
/*To delete users from the Queue when removed*/
private void deleteUserFromGroups(list<SelectOption> listSelectOptionExistingGroupsToDelete, list<SelectOption> listSelectOptionGroupsToDelete){
    if(listSelectOptionExistingGroupsToDelete != NULL){
        User usrSelected = mapUserMatchedtoSearch.containsKey(strIdOfSelectedUser) ?  mapUserMatchedtoSearch.get(strIdOfSelectedUser) : new User();
            list<SelectOption> lstQueuesToBeDeletedFromUser = listSelectOptionGroupsToDelete;
            Set<String> setOldQueueNamesToDelete = new Set<String>();
            Set<String> setNewQueueNamesToDelete = new Set<String>();
            Set<String> setDeleteQueueNames = setOldQueueNamesToDelete;
            for(SelectOption objOldQueueToDelete : listSelectOptionExistingGroupsToDelete ){
                setOldQueueNamesToDelete.add(objOldQueueToDelete.getValue());
            }
            for(SelectOption objNewQueueToDelete : listSelectOptionGroupsToDelete){
                setNewQueueNamesToDelete.add(objNewQueueToDelete.getValue());
            }
            for(String queueToBeDeleted:setNewQueueNamesToDelete ){
                if(setDeleteQueueNames.contains(queueToBeDeleted)){
                    setDeleteQueueNames.remove(queueToBeDeleted);
                }
            }
            System.debug('Finally the list of queues to be deleted '+setDeleteQueueNames);
            if(setDeleteQueueNames!=NULL){
                list<QueueSobject> lstQueToBeDeleted = [select QueueId from QueueSobject Where SobjectType='Case' and Queue.Name in :setDeleteQueueNames];
                Set<Id> setIdDeletion = new Set<Id>();
                for(QueueSobject objQueueIdDeletion : lstQueToBeDeleted){
                    setIdDeletion.add(objQueueIdDeletion.QueueId);
                }
                System.debug('List that needs to be deleted' +lstQueToBeDeleted);
                if(!lstQueToBeDeleted.isEmpty()){
                    list<GroupMember> listGrpMemToBeDeleted = [Select Id from GroupMember where GroupId in :setIdDeletion and UserOrGroupId = :usrSelected.Id  ];
                    System.debug('List of queues to be deleted' +listGrpMemToBeDeleted);
                    try{
                        delete listGrpMemToBeDeleted;
                        } catch(DmlException dmlE){
                     ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error when removing user from Queue')); 
                    }
            }
         }
    }
    
}
/*Adding selected users to the selected Queue*/
private void addUserToGroups(list<SelectOption> listSelectOptionExistingGroups, list<SelectOption> listSelectOptionSelectedGroups){
        if( listSelectOptionExistingGroups != NULL && listSelectOptionSelectedGroups != NULL && !listSelectOptionSelectedGroups.isEmpty()){
            User usrSelected = mapUserMatchedtoSearch.containsKey(strIdOfSelectedUser) ?  mapUserMatchedtoSearch.get(strIdOfSelectedUser) : new User();
            list<SelectOption> lstQueuesToBeAddedToUser = listSelectOptionSelectedGroups;
            Set<String> setOldQueueNames = new Set<String>();
            Set<String> setNewQueueNames = new Set<String>();
            Set<String> setAddQueueNames = setNewQueueNames;
            Set<String> setDelQueueNames = setNewQueueNames;
            for(SelectOption objOldQueue : listSelectOptionExistingGroups ){
                setOldQueueNames.add(objOldQueue.getValue());
            }
            for(SelectOption objNewQueue : listSelectOptionSelectedGroups){
                setNewQueueNames.add(objNewQueue.getValue());
            }
            for(String queueToBeAdded:setOldQueueNames ){
                if(setAddQueueNames.contains(queueToBeAdded)){
                    setAddQueueNames.remove(queueToBeAdded);
                }
            }
            System.debug('Queues to be added ' +setAddQueueNames +'To User' +usrSelected);
            if(setAddQueueNames!=null){
            
            list<QueueSobject> lstQueToBeAdded = [select QueueId from QueueSobject Where SobjectType='Case' and Queue.Name in :setAddQueueNames];
            System.debug('List of queues that should be added'+lstQueToBeAdded);
            if(!lstQueToBeAdded.isEmpty()){
            List<GroupMember> listGroupMemberToInsert = new List<GroupMember>();
            for(QueueSobject objAddUsers: lstQueToBeAdded){
                GroupMember objGrpMemToBeAdded = new GroupMember();
                objGrpMemToBeAdded.GroupId = objAddUsers.QueueId;
                objGrpMemToBeAdded.UserOrGroupId = usrSelected.Id;
                listGroupMemberToInsert.add(objGrpMemToBeAdded);
            }
            try{
                insert listGroupMemberToInsert;
                } catch(DmlException dmlE){
                  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error when Adding User to Queue')); 
              }
            }
            }
        }
    }
/*Clear all the values*/        
public void clearValuesforUserTab(){
        boolShowDropDownOfUsers = false;
        strSearchKeyForQueue = '';
        strIdOfSelectedUser = '';
        listSelectOptionGroupsMultiSelectLeft.clear();
        listSelectOptionGroupsMultiSelectRight.clear();
    //Added by Sreekanth SV Vegi
        buttonValueforSecondTab='Find';
        strNameOfSelectedUser='';
        strSearchKeyForUser='';
    //Ended by Sreekanth SV Vegi
    }
/*Find users based on the searcg*/ 
 public void findUsers(){
        boolShowMessagesForQueueTab = false;
        if(strSelectedQueues != NULL && strSelectedQueues != '' ){
         if((strSelectedSearchOptionForQueueTab != NULL && strSelectedSearchOptionForQueueTab != '') && (strSearchKeyForQueue != NULL && strSearchKeyForQueue != '')){
            updateUsersAvailableForSelection();
            if(listSelOptUsersAvailableForSelection != NULL && listSelOptUsersAvailableForSelection.isEmpty()){
              boolShowMessagesForQueueTab = true;
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'User ' +strSearchKeyForQueue +' is already in the Queue or does not exist'));
          }
         }
         else{
         //Added by Sreekanth SV Vegi
         if (  buttonValue=='Clear')
         {
             listSelOptUsersAvailableForSelection.Clear();
             listSelOptSelectedUsers.Clear();
             buttonValue='Find';
             
         }
         else
         {
         //Ended by Sreekanth SV Vegi
            boolShowMessagesForQueueTab = true;
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,' Please Enter the search content'));
          }
         }
        }
        else{
            boolShowMessagesForQueueTab = true;
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,' Please Select a Queue'));
        }
    }
 /*Updating users available for selection*/
    public void updateUsersAvailableForSelection(){
        list<User> listUserSearchResult = new List<User>();
        list<String> listStringIdsExistingUsersInSelectedTenant = getValuesOfSelectOption(listSelectOptionExistingUsers);
        if(strSelectedSearchOptionForQueueTab != NULL && strSelectedSearchOptionForQueueTab != ''){
          string query = 'select id, Name from User where '+ strSelectedSearchOptionForQueueTab + ' like \'%' + strSearchKeyForQueue + '%\' AND Id !=:listStringIdsExistingUsersInSelectedTenant';
          listUserSearchResult = Database.query(query);
          system.debug('\n query: '+query+'\n listUserSearchResult: '+listUserSearchResult);
          //Added by Sreekanth SV Vegi
          buttonValue='Clear';
          //Ended by Sreekanth SV Vegi
        }

        listSelOptUsersAvailableForSelection = convertListOfNamesinUserToSelectOption(listUserSearchResult).clone();
        system.debug('listSelOptUsersAvailableForSelection: '+listSelOptUsersAvailableForSelection);
        system.debug('\n Existing Users: '+listSelectOptionExistingUsers+'listSelOptSelectedUsers: '+listSelOptSelectedUsers);
    }
}